package com.mall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mall.constant.MessageConstant;
import com.mall.constant.StatusConstant;
import com.mall.dto.GoodsPageQueryDTO;
import com.mall.exception.BaseException;
import com.mall.po.Goods;
import com.mall.mapper.GoodsMapper;
import com.mall.result.PageResult;
import com.mall.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.vo.GoodsPageQueryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author itlxc
 * @since 2024-04-18
 */
@Service
@RequiredArgsConstructor
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    private final GoodsMapper goodsMapper;

    /**
     * 商品分页查询
     * @param goodsPageQueryDTO
     * @return
     */
    @Override
    public PageResult goodsPageQuery(GoodsPageQueryDTO goodsPageQueryDTO) {
        PageHelper.startPage(goodsPageQueryDTO.getPageNum(), goodsPageQueryDTO.getPageSize());
        Page<GoodsPageQueryVO> page = goodsMapper.pageQuery(goodsPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除商品
     * @param ids
     */
    @Transactional
    @Override
    public void deleteGoods(List<Long> ids) {
        // 启售中的商品无法删除
        List<Goods> goodsList = listByIds(ids);
        goodsList.forEach(goods -> {
            if (Objects.equals(goods.getStatus(), StatusConstant.ENABLE)) {
                throw new BaseException(MessageConstant.GOOD_NOT_DEL);
            }
        });
        removeBatchByIds(ids);
    }

    /**
     * 启售、禁售商品
     * @param status
     * @param id
     */
    @Override
    public void startOrStopGood(Integer status, Long id) {
        // 如果是启售商品，判断该商品的品牌是否为启用状态，否则无法启售
        if (Objects.equals(status, StatusConstant.ENABLE)) {
            Integer brandStatus = goodsMapper.getBrandsStatusById(id);
            if (Objects.equals(brandStatus, StatusConstant.DISABLE)) {
                throw new BaseException(MessageConstant.GOOD_NOT_DEL_BY_BRAND_STATUS);
            }
        }
        Goods goods = Goods.builder()
                        .id(id)
                        .status(status)
                        .build();
        updateById(goods);
    }
}
